package com.wending.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.tencent.bugly.crashreport.CrashReport;
import com.wending.R;
import com.wending.application.MyApplication;
import com.wending.base_method.ProcessMethod;
import com.wending.bean.User;
import com.wending.config.Constant;
import com.wending.main_page.CenterActivity;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.List;
import java.util.Map;

/**
 * Created by 张英杰 on 2017/1/23.
 */

public class LoginFragment extends Fragment {
    //    cyh cyh
//admin  admin
//    niutuvip  19941001
    //界面控件
    EditText userName;
    EditText passWord;
    Button loginButton;
    private Context context;

    public interface TunWebViewInterface {
        void IsToWoDe(boolean b);
        void TurnWhere(int positon);//0 首页 1注册2登录 -1后台登录后跳转当前页面
    }

    private TunWebViewInterface tunWebViewInterFace;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
        try {
            tunWebViewInterFace = (TunWebViewInterface) context;
        } catch(Exception e) {
            throw new ClassCastException("Hosting activity must implement TunWebViewInterface");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (DataSupport.findFirst(User.class) != null&&TextUtils.isEmpty(Constant.localCookie)) {
            Login();
        }
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        initView(view);
        return view;
    }

    private boolean loginnng=true;

    /**
     * 初始化界面
     */
    private void initView(View view) {
        userName = (EditText) view.findViewById(R.id.login_et_username);
        passWord = (EditText) view.findViewById(R.id.login_et_password);
//        mWebView = (WebView) view.findViewById(R.id.webview);
        loginButton = (Button) view.findViewById(R.id.login_bt_login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(userName.getText().toString().trim()) || TextUtils.isEmpty(passWord.getText().toString().trim())) {
                    Toast.makeText(context, "请输入账号和密码...", Toast.LENGTH_SHORT).show();
                } else {
                    if (loginnng){
                        userValidation(userName.getText().toString().trim(), passWord.getText().toString().trim());
                    }
                }
            }
        });
        view.findViewById(R.id.register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tunWebViewInterFace.TurnWhere(1);
            }
        });
    }

    private void Login() {
        List<User> all = DataSupport.findAll(User.class);
        if (all != null && all.size() > 0 && all.get(0) != null) {
            User user = all.get(0);
            String url = Constant.Login + "?password=" + user.getPassword() + "&username=" + user.getUsername();
            StringRequest loginRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            }){
                //重写parseNetworkResponse方法，返回的数据中 Set-Cookie:***************;
                //其中**************为session id
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
//                return super.parseNetworkResponse(response);
                    Response<String> superResponse = super
                            .parseNetworkResponse(response);
                    Map<String, String> responseHeaders = response.headers;
                    String rawCookies = responseHeaders.get("Set-Cookie");
                    //Constant是一个自建的类，存储常用的全局变量
                    Constant.localCookie = rawCookies.substring(0, rawCookies.indexOf(";"));
                    Log.d("新的sessionid", "LLLLogin======" + Constant.localCookie);
//                    tunWebViewInterFace.TurnWhere(-1);
                    return superResponse;
                }
            };
            MyApplication.requestQueue.add(loginRequest);
            MyApplication.requestQueue.start();
        }
    }


    /**
     * 用户输入的账号密码 验证 user userValidation(用户验证)
     */
    protected void userValidation(final String str_user_name, final String str_user_pwd) {
        loginnng=false;
        String url = Constant.Login + "?password=" + str_user_pwd + "&username=" + str_user_name;
        StringRequest loginRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dealResponse(s, str_user_name, str_user_pwd);
                loginnng=true;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                loginnng=true;
                Log.i("volleyError==", volleyError.toString());
                Toast.makeText(context, "登录失败",
                        Toast.LENGTH_SHORT).show();
            }
        }){
            //重写parseNetworkResponse方法，返回的数据中 Set-Cookie:***************;
            //其中**************为session id
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
//                return super.parseNetworkResponse(response);
                Log.d("LLLLLLogin", "sessionid====---------" + response.toString());
                Response<String> superResponse = super
                        .parseNetworkResponse(response);
                Map<String, String> responseHeaders = response.headers;
                String rawCookies = responseHeaders.get("Set-Cookie");
                //Constant是一个自建的类，存储常用的全局变量
                Constant.localCookie = rawCookies.substring(0, rawCookies.indexOf(";"));
                Log.d("LLLLLLogin", "sessionid====---------" + Constant.localCookie);
                return superResponse;
            }
        };
        loginRequest.setRetryPolicy(new DefaultRetryPolicy(8 * 1000, 1, 1.0f));
        MyApplication.requestQueue.add(loginRequest);
        MyApplication.requestQueue.start();
    }


    /**
     * 临时测试保存返回一个List
     * 解析并保存用户信息
     * 0 成功
     * 1 失败
     */
    private void dealResponse(String s, String str_user_name, final String str_user_pwd) {
        if (!TextUtils.isEmpty(s)) {
            Log.i("response===",s+"");
            try {
                JSONObject object = new JSONObject(s);
                String msg = (String) object.get("msg");
                if (msg!=null&&(msg.equals("0")||msg.equals("1"))) {
                    JSONArray array= (JSONArray) object.get("data");
                    JSONObject o = array.getJSONObject(0);
                    String  userid = (String) o.get("userid");
                    DataSupport.deleteAll(User.class);
                    User user = new User();
                    user.setUserid(userid);
                    user.setPassword(str_user_pwd);
                    user.setUsername(str_user_name);
                    user.save();
                    Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
                    tunWebViewInterFace.IsToWoDe(true);
                }else {
                    Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        } else {
            Toast.makeText(context, "系统忙，请稍后再试", Toast.LENGTH_LONG).show();
        }
    }
}
